package com.lipuwater.agent.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;

import com.blekit.BluetoothClient;
import com.blekit.model.BleGattProfile;
import com.blekit.receiver.listener.BluetoothStateListener;
import com.blekit.search.SearchResult;
import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.ismartlib.ui.dialog.SheetDialog;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.adapter.BaseViewHolder;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.ble.DeviceConn;
import com.lipuwater.agent.ble.DeviceSearch;
import com.lipuwater.agent.ble.listener.ConnListener;
import com.lipuwater.agent.ble.listener.SearchListener;
import com.lipuwater.agent.ui.dialog.LoadingDialog;
import com.lipuwater.agent.ui.utils.BottomDialogUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeviceConnActivity extends BaseLayoutActivity {

    @Bind(R.id.image_ble_radio)
    ImageView imageBleRadio;

    private Timer timer = null;
    private int imagePosition = 0;
    /**
     * Dialog
     */
    private View mDialogView;
    private SheetDialog mSheetDialog;
    private BottomDialogUtils bottomDialogUtils;

    /**
     * 蓝牙操作对象
     */
    private DeviceSearch mDeviceSearch;
    private DeviceConn mDeviceConn;


    private LoadingDialog loading;

    private BluetoothClient mBleClient;

    private int mDevId;//等待安装的工单设备id
    private int mInstallType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_device_conn);
        initTitle();
        ButterKnife.bind(this);
        requestPermission();
        mDevId = getIntent().getIntExtra("devId", 0);
        mInstallType = getIntent().getIntExtra("installType", 0);
    }

    private void initTitle() {
        initTitle(R.drawable.icon_aleft_white, "连接设备指南");
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
    }

    private void init() {
        bottomDialogUtils = new BottomDialogUtils(this);
        mBleClient = MainActivity.mBleClient;
        mBleClient.registerBluetoothStateListener(mBluetoothStateListener);
        mDeviceSearch = new DeviceSearch();
        mDeviceConn = new DeviceConn();
        loading = new LoadingDialog(this, "连接中...");
        if (mBleClient.isBluetoothOpened()) {
            startAnim();
            startFindDevice();
        } else {
            mBleClient.openBluetooth();
        }
    }

    //6.0扫描设备需要申请定位权限
    private void requestPermission() {
        Permission.getInstance(this)
                .requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                .results(new ResultCallBack() {
                    @Override
                    public void result(PermissionsResult result) {
                        if (result.isGranted()) {
                            init();
                        } else {
                            new AlertDialog.Builder(DeviceConnActivity.this).
                                    setTitle("帮助")
                                    .setMessage("请在设置->应用管理->力浦净水->权限管理->打开手机定位\n避免影响正常功能的使用")
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", null).show();
                        }
                    }
                });
    }


    @OnClick(R.id.image_ble_radio)
    public void btnFindDevice() {
        if (timer == null) {
            if (mBleClient.isBluetoothOpened()) {
                startAnim();
                startFindDevice();
            } else {
                mBleClient.openBluetooth();
            }
        }
    }


    private void startFindDevice() {
        mDeviceSearch.search(new SearchListener() {
            @Override
            public void onSearch(List<SearchResult> devices) {
                if (devices.size() > 0) {
                    showDialog(devices);
                } else {
                    Toast("没有查找到设备");
                }
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                    imageBleRadio.setImageResource(R.drawable.img_ble_radio);
                    imagePosition = 0;
                }
            }
        });
    }


    /**
     * 连接设备
     */
    private void connDevice(final SearchResult device) {
        if (!mBleClient.isBluetoothOpened()) {
            Toast("请打开手机蓝牙");
            return;
        }
        mSheetDialog.dismiss();
        loading.showDialog();
        //开始连接设备
        mDeviceConn.conn(device.getAddress(), new ConnListener() {
            @Override
            public void onConn(int code, BleGattProfile profile) {
                loading.dismiss();
                Intent intent = new Intent(DeviceConnActivity.this, DeviceBindingActivity.class);
                intent.putExtra("DeviceMac", device.getAddress());
                intent.putExtra("deviceName", device.getName());
                intent.putExtra("devId", mDevId);
                intent.putExtra("installType", mInstallType);
                startActivity(intent);
                finish();
            }
        });
    }

    private void showDialog(final List<SearchResult> mDatas) {
        mDialogView = bottomDialogUtils.getView(mDatas);
        bottomDialogUtils.onBindItemView(new BottomDialogUtils.ViewHolder() {
            @Override
            public void onBindViewHolder(BaseViewHolder holder, final int position) {
                holder.setText(R.id.text, mDatas.get(position).getName());
                holder.getView(R.id.text).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        connDevice(mDatas.get(position));
                    }
                });
            }
        });
        mSheetDialog = new SheetDialog(this);
        mSheetDialog.setView(mDialogView);
        mSheetDialog.show();
    }

    /**
     * 开始查找设备动画
     */
    private void startAnim() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (imagePosition == 0) {
                            imageBleRadio.setImageResource(R.drawable.img_ble_radio2);
                            imagePosition = 1;
                        } else if (imagePosition == 1) {
                            imageBleRadio.setImageResource(R.drawable.img_ble_radio1);
                            imagePosition = 2;
                        } else {
                            imageBleRadio.setImageResource(R.drawable.img_ble_radio);
                            imagePosition = 0;
                        }
                    }
                });
            }
        }, 0, 500);
    }


    /**
     * 监听蓝牙打开或者关闭情况
     */
    private BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (openOrClosed) {
                startAnim();
                startFindDevice();
            } else {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                    imageBleRadio.setImageResource(R.drawable.img_ble_radio);
                    imagePosition = 0;
                }
            }
        }

    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        try {
            bottomDialogUtils.CancelCallback();
            bottomDialogUtils = null;
        } catch (Exception e) {
        }
        if (mDeviceSearch != null) {
            mDeviceSearch.stopSearch();
        }
        if (mBleClient != null) {
            mBleClient.unregisterBluetoothStateListener(mBluetoothStateListener);
        }
        if (mBleClient != null) {
            mBleClient = null;
        }
        Permission.getInstance(this).unresults();
    }

}
